package com.saturn.report;

import java.util.List;

import org.json.JSONObject;

import com.saturn.app.db.DymaticCondition;
import com.saturn.app.db.ListData;
import com.saturn.app.db.ORMapping;
import com.saturn.app.db.ResultORMapping;
import com.saturn.app.db.SimpleDaoTemplate;
import com.saturn.app.exception.BSException;

public class ReportData {
	private String id;
	private String name;
	private String sqlSrc;

	private static ORMapping<ReportData> mapping = new ResultORMapping<ReportData>();

	public static int add(ReportData data) {
		if (get(data.getId()) != null) {
			throw new BSException("报表数据源ID重复,id=" + data.getId());
		}

		return SimpleDaoTemplate.update(
				"INSERT INTO report_data VALUES(?, ?, ?)", data.getId(),
				data.getName(), data.getSqlSrc());

	}

	public static int edit(ReportData data) {
		return SimpleDaoTemplate
				.update("UPDATE report_data SET name = ?, sqlSrc = ? WHERE id = ?",
						data.getName(), data.getSqlSrc(), data.getId());
	}

	public static ReportData get(String id) {
		return SimpleDaoTemplate.queryOne(
				"SELECT * FROM report_data WHERE id = '" + id + "'", null,
				mapping, ReportData.class);
	}

	public static ListData<ReportData> getReportDatas(ReportData data,
			String start, String offset, String orderBy, String order) {

		DymaticCondition addCondition = new DymaticCondition()
				.addSimpleCondition(data, "id", "name", "sqlSrc");

		int total = SimpleDaoTemplate.queryCount(
				"SELECT count(*) FROM report_data WHERE 1 = 1", addCondition);

		List<ReportData> list = SimpleDaoTemplate.query(
				"SELECT * FROM report_data WHERE 1 = 1", addCondition
						.addCondition("ORDER BY {0} {1}", orderBy, order)
						.addCondition("LIMIT {0}, {1}", start, offset),
				mapping, ReportData.class);

		return new ListData<ReportData>(total, list);
	}

	public static int remove(String id) {
		return SimpleDaoTemplate.update("DELETE FROM report_data WHERE id = ?",
				id);
	}

	public static void removes(String[] ids) {
		if (ids != null) {
			for (String id : ids) {
				remove(id);
			}
		}
	}

	public ReportData() {
	}

	public ReportData(String id, String name, String sqlSrc) {
		this.id = id;
		this.name = name;
		this.sqlSrc = sqlSrc;
	}
	
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getSqlSrc() {
		return sqlSrc;
	}

	public void setSqlSrc(String sqlSrc) {
		this.sqlSrc = sqlSrc;
	}

	@Override
	public String toString() {
		return new JSONObject(this).toString();
	}
}
